package com.qf.smsplatform.search.config;


import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class ElasticsearchConfig {

    @Value("${spring.elasticsearch.hostAndPort}")
    private String hostAndPort;


    @Bean
    public RestHighLevelClient client(){

        List<HttpHost> httpHostList = new ArrayList<>();
        String[] hostAndPortArray = hostAndPort.split(",");
        for (String hostAndPort : hostAndPortArray) {
            int index = hostAndPort.indexOf(":");
            HttpHost httpHost = new HttpHost(hostAndPort.substring(0,index),Integer.valueOf(hostAndPort.substring(index+1)));
            httpHostList.add(httpHost);
        }


        RestClientBuilder restClientBuilder = RestClient.builder(httpHostList.toArray(new HttpHost[httpHostList.size()]));
        RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);

        return  client;

    }
}
